package net.oschina.git.haxteam.zrank.storage;

import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;

import net.oschina.git.haxteam.zrank.main.Main;


public class YamlFile {

	private FileConfiguration config = null;
	private File configFile = null;

	private String fileName;

	public YamlFile(String fileName){
		this.fileName = fileName;
		saveDefaultConfig();
		reloadConfig();
	}

	public FileConfiguration getConfig(){
		if (config == null){
			reloadConfig();
		}
		return config;
	}

	public void reloadConfig() {
		if (configFile == null) {
			configFile = new File(Main.getInstance().getDataFolder(), fileName);
		}
		config = YamlConfiguration.loadConfiguration(configFile);
		try {
			Reader defConfigStream = new InputStreamReader(Main.getInstance().getResource(fileName), "UTF8");
			if (defConfigStream != null) {
				YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
				config.setDefaults(defConfig);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void saveConfig() {
		if (config == null || configFile == null) {
			return;
		}
		try {
			config.save(configFile);
		} catch (IOException ex) {
		}
	}

	private void saveDefaultConfig(){
		if (configFile == null){
			configFile = new File(Main.getInstance().getDataFolder(), this.fileName);
		}
		if (!configFile.exists()){
			Main.getInstance().saveResource(this.fileName, false);
		}
	}
}